package leetcode.code1930;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int countPalindromicSubsequence(String s) {
		char[] cs = s.toCharArray();
		int len = cs.length;
		int[] l = new int[len];
		int L = this.index(cs, 0);
		for (int i = 0; i < len - 1; i++) {
			l[i] = L;
			L |= this.index(cs, i);
		}
		int R = this.index(cs, len - 1);
		int[] hash = new int[26];
		int ans = 0;
		for (int i = len - 2; i > 0; i--) {
			int me = cs[i] - 'a';
			L = l[i];
			int common = L & R;
			int exists = hash[me];
			int add = common & ~exists;
			while (add > 0) {
				int last = (add & 1);
				ans += last;
				add >>= 1;
			}
			hash[me] |= common;
			R |= this.index(cs, i);
		}
		return ans;
	}

	private int index(char[] cs, int i) {
		return 1 << (cs[i] - 'a');
	}

	@Override
	public void debug4() {
		H.compare(1, this.countPalindromicSubsequence("uuuuu"));
		H.compare(3, this.countPalindromicSubsequence("aabca"));
		H.compare(0, this.countPalindromicSubsequence("adc"));
		H.compare(4, this.countPalindromicSubsequence("bbcbaba"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
